package org.apache.jmeter.functions;


import java.security.MessageDigest;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

/**
 * 参数 md5加密
 * @author 刘德龙
 *
 */
public class ParamMD5 extends AbstractFunction {

	private static final Logger log = LoggingManager.getLoggerForClass();

    private static final List<String> desc = new LinkedList<>();

    private static final String KEY = "__paramMD5"; //$NON-NLS-1$


    private final static String enCoding = "utf-8";

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    static {
        desc.add("paramMD5_string"); //$NON-NLS-1$
    }

    private Object[] values;

    public ParamMD5() {
    }


    public static String md5(String text) {
    	String resultString = null;
		try {
			resultString = text;
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes(enCoding)));
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		return resultString.toUpperCase();
	}

    public static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

    private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

    /** {@inheritDoc} */
    @Override
    public String execute(SampleResult previousResult, Sampler currentSampler)
            throws InvalidVariableException {
        String decodeString = "";
        String rawString = ((CompoundVariable) values[0]).execute();
        log.info("-------source String="+rawString);
        decodeString = md5(rawString);
        log.info("-------encypt String="+decodeString);
        return decodeString;
    }

    /** {@inheritDoc} */
    @Override
    public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
        checkParameterCount(parameters, 1);
        values = parameters.toArray();
    }

    /** {@inheritDoc} */
    @Override
    public String getReferenceKey() {
        return KEY;
    }

    /** {@inheritDoc} */
    @Override
    public List<String> getArgumentDesc() {
        return desc;
    }
}
